package com.nmm.demo.controller;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.List;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传管理器，这里我们仅将文件内容向量化后存入es，文件信息暂不处理，后续应当根据文件信息更新向量数据库
 * @author niemingming
 * @Date 2025/6/12
 */
@RestController
@RequestMapping("/open/ai/v1")
public class FileUploadManagerController {

  @Resource
  private TokenTextSplitter tokenTextSplitter;
  @Resource
  private VectorStore vectorStore;

  /**
   * [这里可以结合文档管理，对于文档应该有删除、修改、新增，这里做示例我们就只做了新增。]
   * @param file 文件内容。
   * @return
   * @author niemingming 2025/6/12
   */
  @PostMapping("/upload")
  public String uploadFile(@RequestParam("file")MultipartFile file) throws IOException {
    TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(new InputStreamResource(file.getInputStream()));
    List<Document> sources = tikaDocumentReader.get();
    List<Document> splitDocuments = tokenTextSplitter.apply(sources);
    vectorStore.add(splitDocuments);
    return "success";
  }

}
